import { View } from "@tarojs/components";
import { Button, Empty, Rate, TabPane, Tabs } from "@nutui/nutui-react-taro";
import { useImmer } from "use-immer";
import { PayType, TaskOrderStatus } from "@/apis/__generated/model/enums";
import { Dictionaries } from "@/apis/__generated/model/enums/DictConstants";
import { api } from "@/utils/api-instance";
import { usePageHelper } from "@/hook";
import Taro from "@tarojs/taro";
import { handleWeChatPay } from "@/pages/index/index";
import OrderRow from "@/pages/index/components/order-row";
import { switchPage } from "@/utils/common";
import UserAvatar from "@/components/user/user-avatar";
import { TaskOrderDto } from "@/apis/__generated/model/dto";
import "./order-list.scss";

export default function OrderList() {
  const [activeStatus, setActiveStatus] =
    useImmer<TaskOrderStatus>("TO_BE_PAID");
  const { TO_BE_PAID, TO_BE_ACCEPT, TO_BE_DELIVERED, FINISHED, REFUNDED } =
    Dictionaries.TaskOrderStatus;
  const tabList = [
    TO_BE_PAID,
    TO_BE_ACCEPT,
    TO_BE_DELIVERED,
    FINISHED,
    REFUNDED,
  ];

  const handleTabChange = async (status: TaskOrderStatus) => {
    setActiveStatus(status);
    await reloadPageData({ query: { status: status } });
  };
  const { dataList, reloadPageData } = usePageHelper(
    api.taskOrderForFrontController.query,
    api.taskOrderForFrontController,
    { query: { status: activeStatus } },
  );
  const handleCancel = async (id: string) => {
    Taro.showModal({
      title: "是否确认取消订单",
      success: (actionRes) => {
        if (actionRes.confirm) {
          Taro.showLoading();
          api.taskOrderForFrontController.delete({ id }).then(() => {
            Taro.showToast({
              title: "取消成功",
              icon: "success",
            });
            Taro.hideLoading();
            reloadPageData();
          });
        }
      },
    });
  };
  const handlePay = async (id: string, type: PayType) => {
    if (type == "WALLET_PAY") {
      await api.taskOrderForFrontController.walletPay({ id });
    } else {
      await handleWeChatPay(id);
    }
    await reloadPageData();
  };
  const showDeliver = (
    order: TaskOrderDto["TaskOrderRepository/COMPLEX_FETCHER_FOR_FRONT"],
  ) => {
    if (!order.deliver) return <div></div>;
    return (
      <View
        className="deliver"
        onClick={() =>
          switchPage("/pages/rating/rating-list?id=" + order.deliver?.id)
        }
      >
        <UserAvatar src={order.deliver.avatar}></UserAvatar>
        <div className="info">
          <div className="name">{order.deliver.nickname}</div>
          <div className="sex">
            {Dictionaries.Gender[order.deliver.gender || "PRIVATE"].keyName}
          </div>
        </div>
        <div className="score">
          <Rate value={order.deliver.score} />
        </div>
      </View>
    );
  };
  return (
    <View className="order-list">
      <Tabs className="tabs" value={activeStatus} onChange={handleTabChange}>
        {tabList.map((tab) => {
          return (
            <TabPane
              title={tab.keyName}
              key={tab.keyEnName}
              value={tab.keyEnName}
            >
              {dataList.length ? (
                dataList.map((order) => {
                  return (
                    <View className="order" key={order.id}>
                      <OrderRow
                        order={order}
                        bottom={showDeliver(order)}
                        buttons={
                          order.status == "TO_BE_PAID"
                            ? [
                                <Button
                                  size="small"
                                  plain
                                  key={1}
                                  onClick={() => handleCancel(order.id)}
                                >
                                  取消订单
                                </Button>,
                                <Button
                                  key={2}
                                  size="small"
                                  type="primary"
                                  onClick={() =>
                                    handlePay(
                                      order.id,
                                      order.baseOrder.payment.payType,
                                    )
                                  }
                                >
                                  立即支付
                                </Button>,
                              ]
                            : [
                                <Button
                                  size="small"
                                  plain
                                  key={1}
                                  onClick={() => handleCancel(order.id)}
                                >
                                  取消订单
                                </Button>,
                                order.deliver ? (
                                  <Button
                                    key={2}
                                    size="small"
                                    type="info"
                                    onClick={() =>
                                      switchPage(
                                        "/pages/rating/rating?id=" + order.id,
                                      )
                                    }
                                  >
                                    评价
                                  </Button>
                                ) : (
                                  <div></div>
                                ),
                              ]
                        }
                      ></OrderRow>
                    </View>
                  );
                })
              ) : (
                <Empty />
              )}
            </TabPane>
          );
        })}
      </Tabs>
    </View>
  );
}
